package cn.elwy.rcp.ui.explorer.core.service.impl;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.tmatesoft.svn.core.SVNException;

import cn.elwy.common.exception.RunException;
import cn.elwy.rcp.core.model.ui.progress.ProgressMonitor;
import cn.elwy.rcp.ui.explorer.core.AppContext;
import cn.elwy.rcp.ui.explorer.core.handler.SvnCheckHandler;
import cn.elwy.rcp.ui.explorer.core.handler.SvnUpdateHandler;
import cn.elwy.rcp.ui.explorer.core.service.SvnManageService;
import cn.elwy.rcp.ui.explorer.core.util.SVNClient;
import cn.elwy.rcp.ui.explorer.core.util.SvnUtil;
import cn.elwy.rcp.ui.explorer.core.vo.ProjectConfig;

@Scope("prototype")
@Service(SvnManageService.ID)
public class SvnManageServiceImpl implements SvnManageService {

  /**
   * 根据配置的SVN地址路径，获取需要检出的目录
   * 
   * @param pathList svn相对地址
   * @return 需要检查的地址
   */
  public void checkOut(ProjectConfig projectConfig, ProgressMonitor monitor) {
    SVNClient svnClient = null;
    try {
      svnClient = SvnUtil.getClientManager(projectConfig.getScmUrl(), projectConfig.getScmUser(),
          projectConfig.getScmPassword());
      SvnUpdateHandler packer = new SvnUpdateHandler();
      packer.setSvnClient(svnClient);

      packer.execute(projectConfig, monitor);
    } catch (SVNException e) {
      throw new RunException(e.getMessage(), e);
    } finally {
      if (svnClient != null) {
        svnClient.dispose();
      }
    }
  }

  @Override
  public boolean checkSvnLogin(ProjectConfig projectConfig, ProgressMonitor monitor) {
    SvnCheckHandler handler = AppContext.getBean(SvnCheckHandler.ID);
    return handler.execute(projectConfig, monitor);
  }

  public boolean isURLExist(String url, String username, String password) {
    return SvnUtil.isURLExist(url, username, password);
  }

}
